package com.qf.common.db.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.qf.common.db.config.AliYunOssProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;
import java.util.Objects;

/**
 * 文件上传工具类
 */
@Service
public class FileUploadUtils {
    public static final String IMG_PREFIX_PATH = "images/";
    public static final String IMG_PREFIX_DEFAULT_NAME = "IMG_";
    public static final int RESULT_STATUS_CODE_SUCCESS = 200;
    @Resource
    private OSS oss;
    @Resource
    private AliYunOssProperties aliYunOssProperties;

    /**
     * 路径前缀 文件名称
     *
     * @param multipartFile
     * @return IMG_20230509131231.
     */
    public String uploadImage(MultipartFile multipartFile) {
        try {
            String objectName = getOssKey(Objects.requireNonNull(multipartFile.getOriginalFilename()));
            PutObjectRequest
                    request = new PutObjectRequest(aliYunOssProperties.getBucketName(), objectName, multipartFile.getInputStream());
            request.setProcess("true");
            PutObjectResult putObjectResult = oss.putObject(request);
            if (putObjectResult.getResponse().getStatusCode() != RESULT_STATUS_CODE_SUCCESS) {
                throw new RuntimeException();
            }
            return getImageUrl(objectName);
        } catch (Exception ex) {
            throw new RuntimeException();
        }
    }

    /**
     * 获取上传OSS key
     * 9e586e01d7cb5d135d560c9b2cd32a2e.jpg
     * 获取图片的后缀名
     * //images/20230519/xxx.png
     * IMG_日期_随机(4) + 后缀名
     */
    private String getOssKey(String originalFilename) {
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String currentDate = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String number = RandomUtil.randomNumbers(4);
        String imageName = String.format("%s%s%s%s", IMG_PREFIX_DEFAULT_NAME, currentDate, number, suffixName);
        return String.format("%s%s%s%s", IMG_PREFIX_PATH, DateUtil.format(new Date(), "yyyyMMdd"), "/", imageName);
    }

    private String getImageUrl(String objectName) {
        Date expiration = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000);
        //申请OSS链接
        URL resUrl = oss.generatePresignedUrl(aliYunOssProperties.getBucketName(), objectName, expiration);
        return resUrl.toString();
    }
}
